#include "stm32f10x.h"

#include "delay.h"
#include "gpio.h"
#include "pid.h"
#include "pwm.h"
#include "adc.h"
#include "encoder.h"
#include "move.h"
#include "oled.h"
#include <stdio.h>
#include "Serial.h"

int targetspeed=200;
float Velcity_Kp=1.5,  Velcity_Ki=0.000000035,  Velcity_Kd=0.00000007; //Ïà¹ØËÙ¶ÈPID²ÎÊý

u16 encoder_A,encoder_B;
int Velocity_PWM1,Velocity_PWM2;
u16 adcx;
float vcc;
u16 x,d;



int main(void)
{
    SystemInit(); //ÅäÖÃÏµÍ³Ê±ÖÓÎª72M   
    delay_init();    //ÑÓÊ±º¯Êý³õÊ¼»¯
    Serial_Init(57600);
    OLED_Init();
    adc_Init();				//ADC1µÄ³õÊ¼»¯   
    PWM_Int(1000-1,7.2);      //³õÊ¼»¯pwmÊä³ö 72000 000 /7199+1=10000 
    Encoder_Init_Tim2();
    Encoder_Init_Tim4();
    OLED_ShowString(1,1,"V:");
    OLED_ShowString(2,1,"S:");


  
    while(1)
    {
		delay_ms(300);
		/**************************************************************************/

    x=0;
    if (Serial_RxFlag == 1)
		{
//			OLED_ShowString(4, 1, "                ");
//			OLED_ShowString(4, 1, Serial_RxPacket);
      if(Serial_RxPacket[0]=='x')
      {
        OLED_ShowString(4, 1, Serial_RxPacket);
         
         x= (Serial_RxPacket[1] - '0') * 100 + (Serial_RxPacket[2] - '0') * 10 + (Serial_RxPacket[3] - '0');
		 d= (Serial_RxPacket[4] - '0') * 100 + (Serial_RxPacket[5] - '0') * 10 + (Serial_RxPacket[6] - '0');
      }
       if(Serial_RxPacket[0]=='d')
      {
//        OLED_ShowString(4, 5, Serial_RxPacket);
//		  d= (Serial_RxPacket[1] - '0') * 100 + (Serial_RxPacket[2] - '0') * 10 + (Serial_RxPacket[3] - '0');
      }
  }
		if(x==0)
			turn();
		delay_ms(500);
        if(x<100)
			x=100;
		else if(x>600)
			x=600;
/**************************************************************************/
		
		
    OLED_ShowNum(1,3,vcc,3);
    OLED_ShowNum(2,3,encoder_A*2.2,5);
    OLED_ShowNum(3,1,Velocity_PWM1,5);
    OLED_ShowNum(3,7,Velocity_PWM2,5);
    OLED_ShowNum(4,7,x,3);
    OLED_ShowNum(4,11,d,3);
        if(d>100)
			stop();
		else track((x-270)/6);
        
        
//        turn();
//       run();
//  right();
//  delay_ms(5000);
//  left();
//  delay_ms(10000);
  Serial_RxFlag = 0;
    }
}